package com.gidgabs.modules.api.controller;

import com.gidgabs.common.utils.ReturnJson;
import com.gidgabs.dto.TbUserDto;
import com.gidgabs.modules.api.service.TbTokenService;
import com.gidgabs.common.annotation.AuthIgnoreApi;
import com.gidgabs.common.utils.R;
import com.gidgabs.common.validator.Assert;
import com.gidgabs.modules.api.service.TbUserService;
import com.gidgabs.modules.entity.TbUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * API授权登录
 * login
 */
@RestController
@RequestMapping("/api/user")
@Api("登录相关")
public class ApiLoginController {
    @Autowired
    private TbUserService userService;
    @Autowired
    private TbTokenService tokenService;

    /**
     * 登录
     */
    /*@AuthIgnoreApi
    @ApiOperation(value = "登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile",value = "账号",dataType = "string",paramType = "form"),
            @ApiImplicitParam(name = "password",value = "密码",dataType = "string",paramType = "form")
    })
    @PostMapping("/login")
    public R login(String mobile, String password) {
        Assert.isBlank(mobile, "phone number is empty");
        Assert.isBlank(password, "password is empty");
        //用户登录
        Integer userId = userService.login(mobile, password);
        //生成token
        Map<String, Object> map = tokenService.createToken(userId);
        TbUser tbUser = new TbUser();
        tbUser.setUserId(userId);
        TbUser user = userService.queryObject(tbUser);
//        //过滤敏感数据
//        TbUserNotAllDto tbUserNotAllDto = new TbUserNotAllDto(user);
        map.put("user", user);
        return R.ok(map);
    }*/
    @AuthIgnoreApi
    @ApiOperation(value = "登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "email", value = "邮箱账号", dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "string", paramType = "form")
    })
    @PostMapping("/login")
    public ReturnJson<TbUserDto> login(String email, String password) {
        Assert.isBlank(email, "email number is empty");
        Assert.isBlank(password, "password is empty");
        //用户登录
        TbUserDto tbUserDto = userService.loginEmail(email, password).toDto();
        //生成token
        Map<String, Object> map = tokenService.createToken(tbUserDto.getUserId());
//        //过滤敏感数据
//        TbUserNotAllDto tbUserNotAllDto = new TbUserNotAllDto(user);
        tbUserDto.setToken(String.valueOf(map.get("token")));
        return ReturnJson.success("登录成功", tbUserDto);
    }
}
